package com.masiyi.springsecuritydemo.service;

import com.masiyi.springsecuritydemo.dao.UserDao;
import com.masiyi.springsecuritydemo.entity.UserDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

@Component
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private  UserDao userDao;

//    @Autowired
//    private PasswordEncoder passwordEncoder;



    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDetail userDetail = userDao.loadUserByUsername(username);
        if (ObjectUtils.isEmpty(userDetail)) {
            throw new RuntimeException("用户不存在");
        }
        userDetail.setRoles(userDao.getRolesByUid(userDetail.getId()));
        return userDetail;
    }

    public Boolean insertUser(UserDetail userDetailInfo) {
        //登录的时候在 UsernamePasswordAuthenticationFilter里面解密
//        userDetailInfo.setPassword(passwordEncoder.encode(userDetailInfo.getPassword()));
        return userDao.insertUser(userDetailInfo);
    }
}